﻿/// <reference path="../_ref.js" />

//MVVM
function Attachment(url, type) {
    var self = this;
    self.Url = url;
    self.Type = type;
}
function AddNoteModel() {
    //Properties
    var self = this;
    self.Title = '';
    self.Content = '';
    self.Attachments = ko.observableArray([]);

    //Add 
    self.addAttachment = function (url, type) {
        self.Attachments.push(new Attachment(url, type));
    };

    //Remove
    self.removeAttachment = function (attachment) {
        //Confirm remove
        if (confirm("Remove the attachment?")) {
            self.Attachments.remove(attachment);
        }

        //Hide attachment list if nothing left
        if (self.Attachments().length == 0) showAttachmentList(false);
    };

    //State check
    self.hasChanged = function () {
        return self.Title !== '' || self.Content !== '' || self.Attachments().length > 0;
    }
}

var model = new AddNoteModel();

//Page load
$(document).ready(function () {
    //Init model
    ko.applyBindings(model);

    //Add note
    $(':button[id=btnSaveNote]').click(function () {
        addNote();
    });

    $('#lnkAttach').clickover({
        template: '<div class="popover popover-note-more"><div class="arrow"></div><div class="popover-inner"><div class="popover-content popover-note-content"><p></p></div></div></div>',
        auto_close: 1000 * 10
    });
});

/////////// Helpers ////////////
function addNote() {
    alert(ko.toJSON(model));
}

var listShowed = false;
function showAttachmentList(show) {
    listShowed = show;
    if (show) {
        $('#addNoteAttachmentList').slideDown();
        $('#txtContent').attr("rows", 8);
    }
    else {
        $('#addNoteAttachmentList').hide();
        $('#txtContent').attr("rows", 12);
    }
}

function browseFile() {
    $('#lnkAttach').clickover('forcehide');
    //Sorry iFans ;)
    if ($.isAppleDevice()) {
        toastr.error("Apple's devices do not support uploading files, sorry.");
    }
    else {
        //Show file browser
        $('#' + novoFileUploadId).click();
    }
}

function promptLink() {
    $('#lnkAttach').clickover('forcehide');

    var link = prompt("Please enter the URL", "http://");
    if (link == '') {
        toastr.error("Cannot add empty link.");
    }
    else {
        if ($.isValidUrl(link)) {
            //Show attachment list if need
            if (!listShowed)
                showAttachmentList(true);

            //Then add to the list
            model.addAttachment(link, "URL");
        }
        else {
            toastr.error("Invalid link. Links should start with http://");
        }
    }
}

//Handle note file upload
function novoUpload() {
    if ($.isBigFile(novoFileUpload[0].files[0])) {
        toastr.error("File is too big. Maximum size is " + (maxRequestSize / 1000 / 1024).toFixed(2) + " MBytes.");
    }
    else {
        novoFileUpload.upload(
            'Note/Upload',
            'json',
            function (data) {
                //Reset upload
                novoFileUpload.val('');
                //Parse result
                var result = $.parseJSON(data);
                $('#txtContent').val(result.Data);
                //And process
                switch (result.Type) {
                    case 'Error':
                        toastr.error(result.Message);
                        break;
                    case 'Success':
                        toastr.success(result.Message);
                        model.addAttachment(result.Data, 'File');
                        if (!listShowed) showAttachmentList(true);
                        break;
                }
            }
        );
    }
}

//Confirm close / discard changes
$('#modalAddNote').on('hide', function () {
    if (model.hasChanged()) {
        if (!confirm("Discard changes?")) {
            return false;
        }
    }

    attachFileUpload(false);
})

//Attach a file upload
$('#modalAddNote').on('shown', function () {
    attachFileUpload(true);
})

